﻿using YunQue.WebApi.Common;

namespace YunQue.WebApi
{
    /// <summary>
    /// 程序启动类
    /// </summary>
    public class WebStartup
    {
        /// <summary>
        /// 构造函数
        /// </summary>
        public WebStartup()
        {
        }
        /// <summary>
        /// 注册服务
        /// </summary>
        /// <param name="service"></param>
        public void ConfigureServices(IServiceCollection service)
        {
            //允许跨域
            service.AddCors(options =>
            {
                options.AddPolicy("any", builder =>
                {
                    builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader();
                });
            });
            service.AddFilterConfig();
            service.AddEndpointsApiExplorer();

            service.AddSwaggerConfig();
            service.AddJwtConfig();

            service.AddHttpContextAccessor();
            service.AddScoped<LogHelper>();
            //注册用户上下文，用于获取用户信息
            service.AddScoped<UserContext>();
            //注册数据库上下文
            service.AddScoped<YunQueDbContext>();
            //注册db context工厂
            service.AddScoped<IDbContextFactory, YunQueDbContextFactory>();
            //注册BaseService
            service.AddScoped<YunQueBaseService>();
            //注册所有实现了IScoped ISingleton ITransient的服务
            service.AddAllDI();
            service.AddSingleton<RouteAttributeLoader>();

        }
        /// <summary>
        /// 启用中间件
        /// </summary>
        /// <param name="app"></param>
        public void Configure(WebApplication app)
        {
            app.UseSwagger();
            app.UseSwaggerUI(options =>
            {
                SwaggerGroupSetting.GroupList.ForEach(item =>
                {
                    options.SwaggerEndpoint($"/swagger/{item.GroupName}/swagger.json", item.Title);
                });
            });
            
            app.UseAuthentication();
            app.UseAuthorization();
            app.UseWebAppCustomConfig();
            app.MapControllers();
            // 加载路由和 Attribute 数据
            var routeAttributeLoader = app.Services.GetRequiredService<RouteAttributeLoader>();
            var routeAttributes = routeAttributeLoader.LoadRouteAttributes();
            // 初始化路由属性缓存
            RouteAttributeCache.Initialize(routeAttributes);
            app.Run();
        }
    }
}
